package net.qhzw.geologr5.gis.service.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import net.qhzw.geologr5.gis.common.framework.exception.CustomException;
import net.qhzw.geologr5.gis.common.framework.utils.FileUtils;
import net.qhzw.geologr5.gis.common.framework.utils.JsonResult;
import net.qhzw.geologr5.gis.common.framework.utils.StringUtils;
import net.qhzw.geologr5.gis.service.system.component.FileTemplate;
import net.qhzw.geologr5.gis.service.system.entity.City;
import net.qhzw.geologr5.gis.service.system.entity.ProjectLegend;
import net.qhzw.geologr5.gis.service.system.entity.ProjectMap;
import net.qhzw.geologr5.gis.service.system.mapper.*;
import net.qhzw.geologr5.gis.service.system.pojo.ProjectMapTem;
import net.qhzw.geologr5.gis.service.system.query.ProjectMapQuery;
import net.qhzw.geologr5.gis.service.system.service.ProjectMapServer;
import net.qhzw.geologr5.gis.service.system.utils.MultipartFileToFile;
import net.qhzw.geologr5.gis.service.system.utils.TxtUtil;
import net.qhzw.geologr5.gis.service.system.vo.project.ProjectMapVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;


@Slf4j
@Service
public class ProjectMapServerImpl implements ProjectMapServer {


    @Autowired
    private ProjectMapMapper projectMapMapper;

    @Autowired
    private FileTemplate fileTemplate;

    @Autowired
    private LegendMapper legendMapper; //图例表dao
    @Autowired
    private ProjectMapIconMapper projectMapIconMapper;

    @Autowired
    private ProjectLegendProjectMapper projectLegendProjectMapper;//项目图例中间表

    @Autowired
    private ProjectLegendMapper projectLegendMapper;

    @Autowired
    private CityMapper cityMapper;

    /***
     * 创建项目地图
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult create(ProjectMapVo projectMapVo) {
        log.info("创建项目地图==ProjectMapServerImpl==method:create==param: {}", JSON.toJSONString(projectMapVo));
        try {
            ProjectMap projectMap = new ProjectMap();
            if (projectMapVo.getCountyId() != null && projectMapVo.getCountyId() > 0) {
                projectMap.setCityId(projectMapVo.getCountyId());
            } else if (projectMapVo.getCityVoId() != null && projectMapVo.getCityVoId() > 0) {
                projectMap.setCityId(projectMapVo.getCityVoId());
            } else if (projectMapVo.getProvinceId() != null && projectMapVo.getProvinceId() > 0) {
                projectMap.setCityId(projectMapVo.getProvinceId());
            }
            BeanUtils.copyProperties(projectMapVo, projectMap);
            if (projectMap.getId() != null) {
                int count = projectMapMapper.updateById(projectMap);
                if (count > 0) {
                    return JsonResult.success("修改成功");
                }
                return JsonResult.error();
            }
            //添加项目地图
            if (projectMap.getCreateTime() == null) {
                projectMap.setCreateTime(new Date());
            }
            //上传文件
            //String fileUrl = fileTemplate.fileUpload(file);
            //projectMap.setCoordinatesFile(fileUrl);
            projectMap.setCreateDate(new Date());
            log.info("projectMap:{}", JSON.toJSONString(projectMap));
            int count = projectMapMapper.insert(projectMap);
            if (count > 0) {
                return JsonResult.success("创建成功");
            }
            return JsonResult.error("创建失败");
        } catch (CustomException e) {
            return JsonResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("创建项目地图失败==ProjectMapServerImpl==method:create==errMsg: {}", e.getMessage());
            return JsonResult.error(e.getMessage());
        }

    }


    /***
     * 查看项目地图
     * @return
     */
    @Override
    public JsonResult find(ProjectMapQuery query) {
        log.info("查看项目地图==ProjectMapServerImpl==method:find==param: {}", JSON.toJSONString(query));
        Map<String, Object> result = new HashMap<>();
        PageHelper.startPage(query.getPage(), query.getLimit());
        try {
            if (query.getProjectId() == null || query.getProjectId() <= 0) {
                return JsonResult.success();
            }
            List<ProjectMapVo> projectMapList = projectMapMapper.selectProjectMap(query.getProjectId());

            for (ProjectMapVo projectMapVo : projectMapList) {
                if (projectMapVo.getCity() != null) {
                    City city = cityMapper.selectById(projectMapVo.getCity().getId());
                    if (city != null && city.getLevel() != null && city.getLevel() > 0) {

                        if (city.getLevel() == 1) {
                            projectMapVo.setProvinceId(city.getId());
                            projectMapVo.setProvinceName(city.getName());
                        } else if (city.getLevel() == 2) {
                            City city2 = cityMapper.selectById(city.getPid());
                            projectMapVo.setCityVoId(city.getId());
                            projectMapVo.setCityVoName(city.getName());
                            projectMapVo.setProvinceId(city2.getId());
                            projectMapVo.setProvinceName(city2.getName());
                        } else if (city.getLevel() == 3) {
                            City city2 = cityMapper.selectById(city.getPid());
                            City city3 = cityMapper.selectById(city2.getPid());
                            projectMapVo.setCountyId(city.getId());
                            projectMapVo.setCountyName(city.getName());
                            projectMapVo.setCityVoId(city2.getId());
                            projectMapVo.setCityVoName(city2.getName());
                            projectMapVo.setProvinceId(city3.getId());
                            projectMapVo.setProvinceName(city3.getName());
                        }

                    }

                }


            }

            PageInfo<ProjectMapVo> pageInfo = new PageInfo<>(projectMapList);
            result.put("list", pageInfo.getList());
            result.put("total", pageInfo.getTotal());
            return JsonResult.success(result);
        } catch (Exception e) {
            log.error("查询项目地图失败==ProjectMapServerImpl==method:find==errMsg: {}", e.getMessage());
            return JsonResult.error(e.getMessage());
        }
    }


    /***
     * 删除项目地图
     * @param ids
     * @return
     */
    @Override
    public JsonResult delete(Integer[] ids) {
        log.info("删除项目地图==ProjectMapServerImpl==method:delete==param: {}", JSON.toJSONString(ids));
        try {
            List<Integer> idList = Arrays.asList(ids);
            int count = projectMapMapper.deleteBatchIds(idList);
            if (count > 0) {
                return JsonResult.success();
            }
            return JsonResult.error();
        } catch (Exception e) {
            log.error("删除项目地图失败==ProjectMapServerImpl==method:delete==errMsg: {}", e.getMessage());
            return JsonResult.error(e.getMessage());
        }
    }


    /***
     * 图例上传
     * @param query
     * @return
     */
    @Override
    public JsonResult uploadLegend(ProjectMapQuery query) {
        //上传文件的路径
        try {
            Integer projectMapId = query.getProjectMapId();
            if (projectMapId == null || projectMapId <= 0) {
                return JsonResult.error("地图id null");
            }
            Integer[] legendIds = query.getLegendIds();
            if (legendIds == null || legendIds.length <= 0) {
                return JsonResult.error("图例null");
            }
            List<Integer> list = Arrays.asList(legendIds);
            List<ProjectLegend> projectLegendList = projectLegendMapper.findByIdList(list);
            projectLegendList.forEach(data -> {
                data.setProjectMapId(projectMapId);
                projectLegendMapper.updateById(data);
            });
            return JsonResult.success();
        } catch (Exception e) {
            log.error("图例上传失败==ProjectMapServerImpl==method:uploadLegend==errMsg: {}", e.getMessage());
            return JsonResult.error(e.getMessage());
        }
    }


    /***
     * 地图查看
     * @param query
     * @return
     */
    @Override
    public JsonResult showMap(ProjectMapQuery query) {
        PageHelper.startPage(query.getPage(), query.getLimit());
        Map<String, Object> result = new HashMap<>();
        try {
            List<ProjectMap> projectMapList = projectMapMapper.showMap(query);
            PageInfo<ProjectMap> pageInfo = new PageInfo<>(projectMapList);
            result.put("total", pageInfo.getTotal());
            result.put("list", pageInfo.getList());
            return JsonResult.success(result);
        } catch (Exception e) {
            log.error("地图查看失败==ProjectMapServerImpl==method:showMap==errMsg :{}", e.getMessage());
            return JsonResult.error(e.getMessage());
        }

    }


    /***
     * 图例查看
     * @param query
     * @return
     */
    @Override
    public JsonResult showLegend(ProjectMapQuery query) {
        PageHelper.startPage(query.getPage(), query.getLimit());
        Map<String, Object> result = new HashMap<>();
        try {
            if (StringUtils.isEmpty(query.getFlag())) {
                return JsonResult.error("标识为空");
            }
            if (query.getProjectMapId() == null || query.getProjectMapId() <= 0) {
                return JsonResult.error("参数null");
            }
            List<ProjectLegend> projectLegendList = null;
            if ("show".equals(query.getFlag())) {
                projectLegendList = projectLegendMapper.findProjectMap(query.getProjectMapId());
            }
            if ("conf".equals(query.getFlag())) {
                projectLegendList = projectLegendMapper.findProjectMapIcon(query.getProjectMapId());
            }
            PageInfo<ProjectLegend> pageInfo = new PageInfo<>(projectLegendList);
            result.put("total", pageInfo.getTotal());
            result.put("list", pageInfo.getList());
            return JsonResult.success(result);
        } catch (Exception e) {
            log.error("图例查看失败==ProjectMapServerImpl==method:showLegend==errMsg :{}", e.getMessage());
            return JsonResult.error(e.getMessage(), "ERROR");
        }

    }


    /***
     * ARSGist上传
     */
    @Override
    public JsonResult uploadARSGist(Integer id, MultipartFile file, MultipartFile coordinateFile) {
        try {
            if (coordinateFile == null || coordinateFile.isEmpty()) {
                return JsonResult.error("请上传元数据文件");
            }
            //MultipartFile转file
            File file1 = MultipartFileToFile.multipartFileToFile(coordinateFile);
            //读取地图元数据文件
            List<String> fileContent = TxtUtil.getFileContent(file1);
            //获取经纬度
            Map<String, String> fileContent1 = TxtUtil.getFileContent(fileContent);

            ProjectMap projectMap = projectMapMapper.selectById(id);
            if (projectMap == null) {
                return JsonResult.error("暂无数据");
            }
            //设置地图经纬度
            projectMap.setUlCornerLongitude(fileContent1.get("ULCORNERLONGITUDE"));
            projectMap.setUlCornerLatitude(fileContent1.get("ULCORNERLATITUDE"));
            projectMap.setUrCornerLongitude(fileContent1.get("URCORNERLONGITUDE"));
            projectMap.setUrCornerLatitude(fileContent1.get("URCORNERLATITUDE"));
            projectMap.setLrCornerLongitude(fileContent1.get("LRCORNERLONGITUDE"));
            projectMap.setLrCornerLatitude(fileContent1.get("LRCORNERLATITUDE"));
            projectMap.setLlCornerLongitude(fileContent1.get("LLCORNERLONGITUDE"));
            projectMap.setLlCornerLatitude(fileContent1.get("LLCORNERLATITUDE"));

            //添加ARSGist
            //生成缩率图ARSGist
            File aRSGistFile = MultipartFileToFile.multipartFileToFile(file);
            Thumbnails.of(aRSGistFile).scale(0.1)
                    .toFile(aRSGistFile);
            MultipartFile thumbnailFFile = MultipartFileToFile.getMulFileByPath(aRSGistFile.toString());
            String thumbnailPath = fileTemplate.fileUpload(thumbnailFFile);
            if (thumbnailPath != null && !StringUtils.isEmpty(thumbnailPath)) {
                projectMap.setThumbnail(thumbnailPath);
            }
            //删除零时文件
            MultipartFileToFile.delteTempFile(aRSGistFile);
            MultipartFileToFile.delteTempFile(file1);
            //上传ARSGist
            String fileUrl = fileTemplate.fileUpload(file);
            if (!StringUtils.isEmpty(fileUrl)) {
                projectMap.setArsgist(fileUrl);
            }
            projectMap.setFileSize(FileUtils.getFileSize(file.getSize()));
            String resolution = this.getResolution(file);
            //设置ARSGist分辨率
            if (resolution != null && !StringUtils.isEmpty(resolution)) {
                projectMap.setResolution(resolution);
            }
            projectMapMapper.updateById(projectMap);
            return JsonResult.success();
        } catch (Exception e) {
            log.error("上传图例失败==ProjectMapServerImpl==method:showLegend==errMsg :{}", e.getMessage());
            return JsonResult.error(e.getMessage(), "ERROR");
        }
    }


    /****
     * 复制项目地图
     * @param id
     * @return
     */
    @Override
    public JsonResult copy(Integer id) {
        ProjectMap projectMap = projectMapMapper.selectById(id);
        if (projectMap == null) {
            return JsonResult.error("参数有误");
        }
        int maxId = projectMapMapper.selectIdMax();
        ProjectMapTem tem = new ProjectMapTem();
        BeanUtils.copyProperties(projectMap, tem);
        ProjectMap projectMapNew = new ProjectMap();
        projectMapNew.setId(maxId + 1);
        BeanUtils.copyProperties(tem, projectMapNew);
        int row = projectMapMapper.insert(projectMapNew);
        return JsonResult.result(row, "复制失败");
    }


    /***
     * 上传坐标系文件
     * @param id
     * @param file
     * @return
     */
    @Override
    public JsonResult uploadCoordinatesFile(Integer id, MultipartFile file) {
        try {
            ProjectMap projectMap = projectMapMapper.selectById(id);
            if (projectMap == null) {
                return JsonResult.error("参数有误");
            }
            String fileUrl = fileTemplate.fileUpload(file);
            if (fileUrl != null && !StringUtils.isEmpty(fileUrl)) {
                projectMap.setCoordinatesFile(fileUrl);
                int row = projectMapMapper.updateById(projectMap);
                return JsonResult.result(row, "上传坐标系文件失败");
            }
        } catch (Exception e) {
            log.error("上传坐标系文件==ProjectMapServerImpl==method:uploadCoordinatesFile==errMsg :{}", e.getMessage());
            return JsonResult.error(e.getMessage());
        }
        return JsonResult.error("上传坐标系文件失败");

    }


    /***
     * 获取上传图片的分辨率
     * @return
     */
    private String getResolution(MultipartFile file) throws IOException {
        if (file == null || file.getSize() <= 0) {
            return null;
        }
        BufferedImage image = ImageIO.read(file.getInputStream());
        //如果image=null 表示上传的不是图片格式
        if (image == null) {
            return null;
        }
        //判断图片是否是正方形
        int height = image.getHeight();
        int width = image.getWidth();
        String resolution = width + "×" + height;
        return resolution;
    }


}
